/*
 * Copyright (c) 2012 Universidad Antonio de Nebrija.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Apache License v2.0
 * which accompanies this distribution, and is available at
 * http://www.apache.org/licenses/LICENSE-2.0.html
 * 
 * Contributors:
 *    Universidad Antonio de Nebrija - initial API, implementation and documentation
 */
package com.nebrija.riif.parser;

import org.antlr.runtime.tree.Tree;

import com.nebrija.riif.model.Component;
import com.nebrija.riif.model.RIIFElement;
import com.nebrija.riif.model.RootClass;

/**
 * Parse the component token from the tree and convert it into the object from the RIIF model
 * @author asanchep
 *
 */
public class ComponentElementProcessor implements RIIFParserProcessor{

	private static final String EXTENDS = "extends";
	@Override	
	public RIIFElement apply(RIIFElement container, Tree t) {
		// The component can only be included into a RootClass
		if(! (container instanceof RootClass)){
			return null;
		}
		RootClass root = (RootClass)container;
		// Get the id, create it and add it to the RootClass
		String id = t.getChild(0).getText();
		Component c = new Component(id);
		String extend = t.getChild(1).getText();
		if(extend.contains(EXTENDS)){
			String name = t.getChild(1).getChild(0).getText();
			RIIFElement element = root.getElement(name);
			if(element!=null && element instanceof Component){
				c.setParent((Component)element);
			}
		}
		root.addElement(c);
		return c;
	}
	
}
